var zlib = require('zlib');
var stream = require('stream');
var encoding = require('./encoding');

var util = {
	jsonRespond : function(response, json, options){
		options = options || {};

		var defaultResponseHeader = {
			'Content-Type':'application/json;charset=UTF-8'
		};
		for(var p in options){
			defaultResponseHeader[p] = options[p]
		}

		response.writeHead(options.status || '200',defaultResponseHeader);
		response.end(json?JSON.stringify(json):'','utf-8');
	},

	compressRespond: function(request ,response, json, options){
		options = options || {};

		var defaultResponseHeader = {
			'Content-Type':'application/json'
		};

		var contentEncoding = encoding.checkEncoding(request);

		for(var p in options){
			defaultResponseHeader[p] = options[p];
		}
        defaultResponseHeader['Content-Encoding'] = contentEncoding;
        //压缩
        var str = json?JSON.stringify(json):'';
        zlib[contentEncoding](str,function(err,buffer){
            defaultResponseHeader['Content-Length'] = buffer.length;
            response.writeHead(options.status || '200', defaultResponseHeader);
            response.end(buffer, 'UTF-8');
        });
	}
};

module.exports = util;
